package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.service.ShoppingCarService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.connection.SortParameters;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private ShoppingCarMapper shoppingCarMapper;

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private SetmealMapper setmealMapper;

    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 用户下单接口
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {

        //处理业务异常：购物车为空？地址簿为空？（若通过测试数据提交，则没有小程序帮助校验，需要自行校验，代码健壮性）
        //判断地址簿是否为空
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null)
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        //判断购物车是否为空
        Long userId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);
        List<ShoppingCart> list = shoppingCarMapper.list(shoppingCart);
        if (list == null || list.size() == 0)
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);

        //判断地址是否超出门店配送范围（5km）
        checkIfOutOfDistance(addressBook.getDetail());

        //创建order对象
        Orders orders = new Orders();
        //属性拷贝
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        //设置参数
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));   //通过当前时间获取订单号
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());
        orders.setUserId(BaseContext.getCurrentId());

        //向order表中插入数据
        orderMapper.insert(orders);

        //向order_details表中插入n条数据（根据购物车商品获得）
        List<OrderDetail> orderDetails = new ArrayList<>();
        for (ShoppingCart cart : list) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            log.info("当前订单中菜品数量为：{}", orderDetail.getNumber());
            orderDetail.setOrderId(orders.getId());
            orderDetails.add(orderDetail);
        }
        orderDetailMapper.insertBatch(orderDetails);

        //清空当前用户购物车数据（若点击支付）
        shoppingCarMapper.clean(userId);

        //封装VO响应结果
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();

        return orderSubmitVO;
    }


    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getUserByOpenid(String.valueOf(userId));

        /*//调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );*/

        JSONObject jsonObject = new JSONObject();

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        paySuccess(ordersPaymentDTO.getOrderNumber());

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

        //通过websocket向浏览器发送消息
        //创建请求对象
        Map params = new HashMap<>();
        params.put("type", 1);
        params.put("orderId", orders.getId());
        params.put("content", "订单号：" + outTradeNo);
        //将请求对象封装为JSON
        String jsonString = JSON.toJSONString(params);
        //将请求发送给客户端
        webSocketServer.sendToAllClient(jsonString);
    }


    /**
     * 历史订单分页查询
     * @param page
     * @param pageSize
     * @param status
     * @return
     */
    @Override
    public PageResult historyPage(int page, int pageSize, Integer status) {
        PageHelper.startPage(page, pageSize);

        //创建与数据库交互的分页查询对象，接收前端的请求参数并进行封装
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        ordersPageQueryDTO.setStatus(status);

        //通过该分页查询对象查询数据库
        Page<Orders> p = orderMapper.listByPageQuery(ordersPageQueryDTO);

        //遍历当前分页的order数据，分别获取其中的订单详情集合，并将order数据与当前订单详情进行封装成VO
        List<OrderVO> orderVOS = new ArrayList<>(); //封装响应数据的集合
        for (Orders orders : p) {
            //首先将orders的部分数据复制给当前VO对象
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(orders, orderVO);

            //通过当前order查询订单详情，并将详情封装到当前VO中
            List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(orders.getId());
            orderVO.setOrderDetailList(orderDetails);

            //将当前封装好的VO放入集合中
            orderVOS.add(orderVO);
        }

        //我们要返回的result是当前的VO，所以不能像之前一样使用p.getResult！
        return new PageResult(p.getTotal(), orderVOS);
    }




    /**
     * 查询当前订单的详细信息
     * @param id
     * @return
     */
    @Override
    public OrderVO selectDetail(Long id) {
        OrderVO orderVO = new OrderVO();

        //首先查询订单基本信息
        Orders orders = orderMapper.getById(id);
        //拷贝基本信息
        BeanUtils.copyProperties(orders, orderVO);
        //查询订单详细内容
        List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(id);
        //封装
        orderVO.setOrderDetailList(orderDetails);

        return orderVO;
    }


    /**
     * 取消订单
     * @param id
     */
    @Override
    public void cancel(Long id) throws Exception {
        //查询订单信息
        Orders orders = orderMapper.getById(id);

        //判断订单是否存在，不存在则报错
        if (orders == null)
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);

        //判断订单状态，除非为待付款和待接单，否则均需要与商家打电话协商，即返回对应报错
        if (orders.getStatus() > 2 && orders.getStatus() != 6)
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);

    /*//若订单已支付，需要进行退款
    if (orders.getStatus() == 2){
        //调用微信支付退款接口
        weChatPayUtil.refund(
                orders.getNumber(), //商户订单号
                orders.getNumber(), //商户退款单号
                new BigDecimal(0.01),//退款金额，单位 元
                new BigDecimal(0.01));//原订单金额

        //支付状态修改为 退款
        orders.setPayStatus(Orders.REFUND);
    }*/

        //修改订单状态
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason("用户取消订单");
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }


    /**
     * 再来一单
     * @param id
     */
    @Override
    public void repetition(Long id) {
        //通过订单id查询到具体的菜品信息
        List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(id);

        //再来一单实际上就是生成一个购物车数据！
        List<ShoppingCart> shoppingCarts = new ArrayList<>();

        //遍历菜品信息，添加到购物车中
        for (OrderDetail orderDetail : orderDetails) {
            ShoppingCart shoppingCart = new ShoppingCart();

            //属性拷贝
            BeanUtils.copyProperties(orderDetail, shoppingCart, "id");

            shoppingCart.setUserId(BaseContext.getCurrentId());
            //设置新物品数量为一
            shoppingCart.setNumber(1);
            //设置添加时间
            shoppingCart.setCreateTime(LocalDateTime.now());

            shoppingCarts.add(shoppingCart);    //将当前购物车数据加入集合中
        }

        /*List<ShoppingCart> shoppingCarts = orderDetails.stream().map(orderDetail -> {
                        ShoppingCart shoppingCart = new ShoppingCart();
                        BeanUtils.copyProperties(orderDetail, shoppingCart, "id");
                        shoppingCart.setUserId(BaseContext.getCurrentId());
                        //设置新物品数量为一
                        shoppingCart.setNumber(1);
                        //设置添加时间
                        shoppingCart.setCreateTime(LocalDateTime.now());
                    return shoppingCart;
                }
        ).collect(Collectors.toList());*/

        //批量插入，节约性能
        shoppingCarMapper.insertBatch(shoppingCarts);
    }


    /**
     * 订单搜索
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());

        //获取分页查询结果
        Page<Orders> orders = orderMapper.listByPageQuery(ordersPageQueryDTO);

        //通过stream流进行VO的封装
        List<OrderVO> orderVOS = orders.stream().map(order ->{
            //将当前order封装到orderVO中
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(order, orderVO);

            //查询订单详情并进行封装
            List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(order.getId());

            orderVO.setOrderDetailList(orderDetails);

            return orderVO;
        }).collect(Collectors.toList());

        return new PageResult(orders.getTotal(), orderVOS);
    }


    /**
     * 各个状态订单数量统计
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {
        //查询全部订单
        List<Orders> orders = orderMapper.listByPageQuery(new OrdersPageQueryDTO());

        Integer toBeConfirmed = 0;  //待接单
        Integer confirmed = 0;  //待派送
        Integer deliveryInProgress = 0; //派送中
        //统计订单状态
        for (Orders order : orders) {
            Integer status = order.getStatus();
            if (status == Orders.CONFIRMED)
                confirmed += 1;
            else if (status == Orders.TO_BE_CONFIRMED)
                toBeConfirmed += 1;
            else if (status == Orders.DELIVERY_IN_PROGRESS)
                deliveryInProgress += 1;
        }

        //封装给VO
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);

        return orderStatisticsVO;
    }


    /**
     * 接单，即修改订单状态为已接单
     * @param ordersConfirmDTO
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Long id = ordersConfirmDTO.getId();

        //通过id查询订单信息
        Orders orders = orderMapper.getById(id);

        //查询订单状态，只有当订单状态为2时才执行操作
        Integer status = orders.getStatus();
        if (status != Orders.TO_BE_CONFIRMED)
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);

        //修改订单状态为已接单，修改数据库信息
        orders.setStatus(Orders.CONFIRMED);
        orderMapper.update(orders);
    }


    /**
     * 拒单
     * @param ordersRejectionDTO
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) throws Exception {
        Orders orders = orderMapper.getById(ordersRejectionDTO.getId());
        log.info("订单id为：{}", ordersRejectionDTO.getId());

        //判断订单状态，只有status = 2时才可以拒单
        if (orders == null || orders.getStatus() != Orders.TO_BE_CONFIRMED)
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);

        //微信退款
        /*//支付状态
        Integer payStatus = orders.getPayStatus();
        if (payStatus == Orders.PAID) {
            //用户已支付，需要退款
            String refund = weChatPayUtil.refund(
                    orders.getNumber(),
                    orders.getNumber(),
                    new BigDecimal(0.01),
                    new BigDecimal(0.01));
            log.info("申请退款：{}", refund);
        }*/

        //更新订单信息
        Orders order = Orders.builder()
                .id(ordersRejectionDTO.getId())
                .rejectionReason(ordersRejectionDTO.getRejectionReason())
                .cancelTime(LocalDateTime.now())
                .status(Orders.CANCELLED)
                .build();

        orderMapper.update(order);
    }


    /**
     * 管理员端取消订单
     * @param ordersCancelDTO
     */
    @Override
    public void cancelByAdmin(OrdersCancelDTO ordersCancelDTO) throws Exception {
        Orders orders = orderMapper.getById(ordersCancelDTO.getId());

        //为用户退款
        //支付状态
        /*Integer payStatus = orders.getPayStatus();
        if (payStatus == 1) {
            //用户已支付，需要退款
            String refund = weChatPayUtil.refund(
                    orders.getNumber(),
                    orders.getNumber(),
                    new BigDecimal(0.01),
                    new BigDecimal(0.01));
            log.info("申请退款：{}", refund);
        }*/

        //修改订单信息，更新数据库
        Orders order = Orders.builder()
                .id(ordersCancelDTO.getId())
                .cancelTime(LocalDateTime.now())
                .cancelReason(ordersCancelDTO.getCancelReason())
                .status(Orders.CANCELLED)
                .build();

        orderMapper.update(order);
    }


    /**
     * 派送订单
     * @param id
     */
    @Override
    public void delivery(Long id) {
        Orders orders = orderMapper.getById(id);

        //判断订单状态是否为已接单
        if (orders == null || orders.getStatus() != Orders.CONFIRMED)
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);

        Orders order = Orders.builder()
                .id(orders.getId())
                .status(Orders.DELIVERY_IN_PROGRESS)
                .build();

        orderMapper.update(order);
    }


    /**
     * 完成订单
     * @param id
     */
    @Override
    public void complete(Long id) {
        Orders orders = orderMapper.getById(id);

        //必须是派送中的订单才能完成
        if (orders == null || orders.getStatus() != Orders.DELIVERY_IN_PROGRESS)
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);

        //设置订单完成时间、订单状态等内容
        Orders order = Orders.builder()
                .id(orders.getId())
                .status(Orders.COMPLETED)
                .deliveryTime(LocalDateTime.now())
                .build();

        orderMapper.update(order);
    }


    /**
     * 判断用户地址与商家地址距离是否超过5km
     * @param userAddress
     */
    //必要参数
    @Value("${sky.baidu.ak}")
    private String ak;
    @Value("${sky.baidu.shopaddress}")
    private String shopAddress;

    //百度地图解析地址的请求路径
    public String URLForAddress = "https://api.map.baidu.com/geocoding/v3";

    //百度地图规划路线的请求路径
    public String URLForDriver = "https://api.map.baidu.com/direction/v2/driving";
    //路线规划失败的报错提示
    public final String DRIVING_FAILED = "配送路线规划失败";

    private void checkIfOutOfDistance(String userAddress){
        //解析商户地址数据
        //创建商家地址的请求参数
        Map shopParams = new HashMap<String, String>();
        shopParams.put("address", shopAddress);
        shopParams.put("output", "json");   //指定请求参数封装格式
        shopParams.put("ak", ak);
        //发起请求，获取商家地址在地图上的位置
        String shopCoordinate = HttpClientUtil.doGet(URLForAddress, shopParams);
        /*
        获取的响应数据如下：
        shopCoordinate = "{"result":{"level":"","confidence":100,"location":{"lng":116.30787799999993,"lat":40.05702706489032},"precise":1,"comprehension":100},"status":0}"
         */
        //解析响应数据，获得经纬度相关信息
        JSONObject shopJSON = JSON.parseObject(shopCoordinate);
        //若解析失败，则获取到的status将！=0
        if (!shopJSON.getString("status").equals("0"))
            throw new OrderBusinessException("店铺地址解析失败");
        JSONObject shopLocation = shopJSON.getJSONObject("result").getJSONObject("location");
        String shopLng = shopLocation.getString("lng");  //经度
        String shopLat = shopLocation.getString("lat");  //纬度
        String shopLatLng = shopLat + "," + shopLng;    //拼接成经纬度，用于路径规划

        //解析用户地址数据
        //创建请求参数
        Map userParams = new HashMap<String, String>();
        userParams.put("address", userAddress);
        userParams.put("ak", ak);
        userParams.put("output", "json");
        //发送请求获取响应结果
        String userCoordinate = HttpClientUtil.doGet(URLForAddress, userParams);
        JSONObject userJSON = JSON.parseObject(userCoordinate);
        //判断是否解析成功
        if (!userJSON.getString("status").equals("0"))
            throw new OrderBusinessException("收货地址解析失败");
        //获取经纬度
        JSONObject userLocation = userJSON.getJSONObject("result").getJSONObject("location");
        String userLng = userLocation.getString("lng");
        String userLat = userLocation.getString("lat");
        String userLatLnt = userLat + "," + userLng;


        //通过路径规划，计算商户与用户间的距离
        Map drivingParams = new HashMap<String, String>();
        drivingParams.put("origin", shopLatLng);
        drivingParams.put("destination", userLatLnt);
        drivingParams.put("steps_info", "0");
        drivingParams.put("ak", ak);
        String drivingResult = HttpClientUtil.doGet(URLForDriver, drivingParams);
        JSONObject drivingJSON = JSON.parseObject(drivingResult);
        //判断是否成功规划路径
        if (!drivingJSON.getString("status").equals("0"))
            throw new OrderBusinessException(DRIVING_FAILED);
        //解析获取其中的距离参数
        JSONObject result = drivingJSON.getJSONObject("result");
        JSONArray jsonArray = (JSONArray) result.get("routes");
        Integer distance = (Integer) ((JSONObject) jsonArray.get(0)).get("distance");   //单位（m）

        //判断路径是否超过5000(m)
        if (distance > 5000)
            throw new OrderBusinessException("超出配送范围");
    }


    /**
     * 用户催单
     * @param id
     */
    @Override
    public void reminder(Long id) {
        Orders orders = orderMapper.getById(id);

        if (orders == null)
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);

        //通过websocket发送请求
        //封装请求参数
        Map map = new HashMap<>();
        map.put("type", 2);
        map.put("orderId", id);
        map.put("content", "用户催单，订单号为：：" + orders.getNumber());
        String jsonString = JSON.toJSONString(map);
        //发起请求
        webSocketServer.sendToAllClient(jsonString);

    }
}
